<template>
	<div v-loading="loading" element-loading-text="加载中" class="wapper">
		<wt-re-request-tip
				:reLoad="load"
				:styles="'top:0;left:0;right:0;bottom:40px;'"
				v-show="isShowReloadTip">
		</wt-re-request-tip>
		<slot></slot>
		<el-pagination
			v-if="showPagination"
			@current-change="handleCurrentChange"
			:page-size="pageSize"
			layout="total, prev, pager, next"
			:total="currentTotal">
		</el-pagination>
	</div>
</template>

<script>
/*
	 基于element-ui的ajax分页列表组件，封装了分页组件以及ajax请求的交互
	 用法：
	 <wt-paged-table>
	 	<!-- 页面渲染的列表数据，可以用vue在前端进行渲染，也可以是服务器端渲染出来的数据 -->
	 </wt-paged-table>
	 Events:
	 	page-loaded
	 */
import Vue from "vue";
import ElementUI from "element-ui";
import WtReRequestTip from "./wt-reRequest-tip";
import request from "winged/utils/axios";

Vue.use(ElementUI);

export default {
	components: { WtReRequestTip },
	name: "wt-paged-table",

	props: {
		// ajax接口用于查询数据的url
		url: {
			type: String
		},
		urlMethod: {
			type: String,
			default: "POST"
		},
		// 是否进行transfer调用
		transfer: false,
		// url接口查询时的当前页参数名
		pageParam: {
			type: String,
			default: "page"
		},
		// 从返回数据中获取结果的字段
		resultParam: {
			type: String,
			default: null
		},
		// 从返回结果中获取记录总数的字段
		countParam: {
			type: String,
			default: "count"
		},
		// url接口查询时的filter参数名
		filterParam: {
			type: String,
			default: "condition"
		},
		filter: {
			type: String,
			default: ""
		},
		//url接口查询时的其它参数
		extraParams: {
			type: Object,
			default: null
		},
		// 第一次渲染时的初始页
		initialPage: {
			type: Number,
			default: 0
		},
		totalSize: {
			type: Number,
			required: false
		},
		sizeParam: {
			type: String,
			default: null
		},
		pageSize: {
			type: Number,
			default: 20
		},
		// 如果为true，则组件在mount后会自动进行一次加载
		refresh: {
			type: Boolean,
			default: false
		},
		showPagination: {
			type: Boolean,
			default: true
		},
		fetch: {
			//自定义请求的方法，会覆盖组件内部的请求方法,fetch必须返回一个promise
			type: Function
		}
	},
	computed: {
		isShowReloadTip() {
			//是否显示加载错误提示，和重新加载按钮
			return !this.loading && this.requestStatus == "fail";
		}
	},
	data() {
		return {
			page: this.initialPage,
			loading: false,
			loadOnMounted: this.refresh,
			currentTotal: this.totalSize,
			//请求状态,success,fail
			requestStatus: false
		};
	},
	watch: {
		totalSize(val) {
			this.currentTotal = val;
		},
		filter: function(newFilter) {
			this.load();
		},
		extraParams(val) {
			this.load();
		},
		refresh(val, oldValue) {
			this.loadOnMounted = val;
		}
	},
	methods: {
		handleCurrentChange: function(currentPage) {
			this.page = currentPage - 1;
			this.load();
		},
		getQueryData: function() {
			let data = {};
			data[this.pageParam] = this.page;
			if (this.filterParam != "") {
				data[this.filterParam] = this.filter;
			}
			if (this.extraParams != null) {
				for (let item in this.extraParams) {
					data[item] = this.extraParams[item];
				}
			}
			if (this.sizeParam) {
				if (this.urlMethod == "DRONE") {
					data[this.pageParam] = data[this.pageParam].toString();
					data[this.sizeParam] = this.pageSize.toString();
				} else {
					data[this.sizeParam] = this.pageSize;
				}
			}
			return data;
		},
		load: function() {
			let vm = this;
			this.loading = true;
			let axios = require("winged/utils/axios");
			if (this.fetch) {
				console.log(
					"getQueryData",
					JSON.stringify(this.getQueryData())
				);
				//使用自定义的请求方法
				this.fetch(this.getQueryData())
					.then(response => {
						console.log("response", response);
						vm.loading = false;
						vm.requestStatus = "success";
						let data = response;
						let total = null;
						if (data.count !== undefined) {
							total = data.count;
						} else if (
							vm.countParam &&
							data.hasOwnProperty(vm.countParam)
						) {
							total = data[vm.countParam];
						}
						if (vm.transfer) {
							// nothing to do.
						} else {
							if (response.data) {
								data = response.data;
							}
						}
						if (typeof data == "string") {
							//如果是JSON字符串格式的数组
							if (!/\[|\]/.test(data) && data.length == 0) {
								data = [];
							} else {
								data = JSON.parse(data);
							}
						}
						if (!Array.isArray(data)) {
							if (data.count !== undefined) {
								total = data.count;
							} else if (
								vm.countParam &&
								data.hasOwnProperty(vm.countParam)
							) {
								total = data[vm.countParam];
							}
							if (vm.resultParam) {
								data = data[vm.resultParam];
							}
						}
						if (total != null) {
							if (typeof total === "string") {
								total = Number(total);
							}
							vm.currentTotal = total;
						}
						vm.loadOnMounted = false;
						vm.$emit("page-loaded", data);
					})
					.catch(err => {
						console.error(err);
						vm.loading = false;
						vm.requestStatus = "fail";
						vm.$message.error("加载出错" + err.message);
					});
				return;
			}
			request(
				this.url,
				this.urlMethod,
				this.getQueryData(),
				this.transfer,
				function(response) {
					vm.loading = false;
					vm.requestStatus = "success";
					let data = response;
					let total = null;
					if (data.count !== undefined) {
						total = data.count;
					} else if (
						vm.countParam &&
						data.hasOwnProperty(vm.countParam)
					) {
						total = data[vm.countParam];
					}
					if (vm.transfer) {
						// nothing to do.
					} else {
						if (response.data) {
							data = response.data;
						}
					}
					if (typeof data == "string") {
						data = JSON.parse(data);
					}
					if (!Array.isArray(data)) {
						if (data.count !== undefined) {
							total = data.count;
						} else if (
							vm.countParam &&
							data.hasOwnProperty(vm.countParam)
						) {
							total = data[vm.countParam];
						}
						if (vm.resultParam) {
							data = data[vm.resultParam];
						}
					}
					if (total != null) {
						if (typeof total === "string") {
							total = Number(total);
						}
						vm.currentTotal = total;
					}
					vm.loadOnMounted = false;
					vm.$emit("page-loaded", data);
				},
				function(error) {
					console.error(error);
					vm.loading = false;
					vm.requestStatus = "fail";
					vm.$message.error("加载出错");
				},
				true
			);
		}
	},
	mounted() {
		if (this.loadOnMounted) {
			this.load();
		}
	}
};
</script>
<style scoped>
.el-pagination {
	display: flex;
	justify-content: center;
	margin-top: 10px;
}
.wapper {
	position: relative;
}
</style>